﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.DataVisualization.Charting;
using Agents.Data;
using System.Globalization;
using System.Threading;

namespace Agents.Admin
{
    public partial class ProfitReport : System.Web.UI.Page
    {
        #region Event Handlers

        /// <summary>
        /// Occurs when the page is loaded
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // Initial binding
            if (!IsPostBack)
            {
                // Populate cmbYears and cmbMonths
                cmbYears.DataSource = Enumerable.Range(1980, 
                                    DateTime.Now.Year - 1979).ToList();
                cmbYears.DataBind();
                cmbYears.SelectedIndex = cmbYears.Items.Count - 1;

                CultureInfo culture = new CultureInfo("he-IL");
                cmbMonths.DataSource = culture.DateTimeFormat.MonthNames.Take(12);
                cmbMonths.DataBind();

                // Default is annual
                radYear.Checked = true;
            }
        }

        /// <summary>
        /// Redirects the admin back to his homepage when the "back" button is pressed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void backBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }

        /// <summary>
        /// Occurs when the admin chooses one of the time ranges options
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void rad_CheckedChanged(object sender, EventArgs e)
        {
            panelSelectYear.Visible = radYear.Checked;
            panelSelectMonth.Visible = radMonth.Checked;
            panelSelectRange.Visible = radRange.Checked;

            lblBalance.Text = "";
        }

        /// <summary>
        /// Occurs when the admin selects "בצע" and shows the graph
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnBuildGraph_Click(object sender, EventArgs e)
        {
            // Get the date range
            DateTime startDate, endDate;
            
            // By year
            if (radYear.Checked)
            {
                int year = Convert.ToInt32(cmbYears.SelectedValue);
                startDate = new DateTime(year, 1, 1);
                endDate = new DateTime(year, 12, 31);
            }

            // By month
            else if (radMonth.Checked)
            {
                int year = DateTime.Now.Year;
                CultureInfo culture = new CultureInfo("he-IL");
                int month = DateTime.ParseExact(cmbMonths.SelectedValue, "MMMM", culture).Month;
                startDate = new DateTime(year, month, 1);
                endDate = new DateTime(year, month, DateTime.DaysInMonth(year, month));
            }

            // By range
            else
            {
                startDate = DateTime.Parse(txtStartDate.Text);
                endDate = DateTime.Parse(txtEndDate.Text);
            }

            BuildGraph(startDate, endDate);
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Creates the pie chart of expenses and profit in these dates
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        private void BuildGraph(DateTime startDate, DateTime endDate)
        {
            Queries queries = new Queries();
            RegionInfo region = new RegionInfo("IL");

            Dictionary<String, double> balanceReport = queries.GetBalance(startDate, endDate);
            profitChart.DataSource = balanceReport;
            profitChart.Series[0].XValueMember = "key";
            profitChart.Series[0].YValueMembers = "value";
            profitChart.DataBind();

            // Set the pie labels to be drawn outside of the pie chart
            profitChart.Series[0]["PieLabelStyle"] = "Outside";

            // Set these other two properties so that you can see the connecting lines
            profitChart.Series[0].BorderWidth = 1;
            profitChart.Series[0].BorderColor = System.Drawing.Color.FromArgb(26, 59, 105);

            // Show value and precent of expenses and profit
            profitChart.Series[0].Label = region.CurrencySymbol + "#VALY{N2}\n#PERCENT{P2}";
            profitChart.Series[0].LegendText = "#AXISLABEL";

            // Show the balance (culture info is used for the correct format)
            CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
            CultureInfo newCulture = new CultureInfo(currentCulture.IetfLanguageTag);
            newCulture.NumberFormat.CurrencyNegativePattern = 13;
            Thread.CurrentThread.CurrentCulture = newCulture;
            lblBalance.Text = (balanceReport["הכנסות"] - balanceReport["הוצאות"]).ToString("c");
        }

        #endregion
    }
}